package com.hktf.uilib.base;

import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hktf.corelib.utils.CommUtils;
import com.hktf.corelib.utils.LogMds;
import com.hktf.corelib.utils.UIUtils;
import com.hktf.uilib.R;

import java.util.ArrayList;
import java.util.List;


public abstract class BaseListPage<T>{
    public Context context;
    public View rootView;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout refresh;
    private LinearLayout llError;
    private LinearLayout llLocationError;
    private FrameLayout flLoading;
    public LinearLayout llEmpty;
    public BaseQuickAdapter adapter;
    private List<T> data;
    private boolean isLoadMore;
    public GetDataCallBack<T> callBack;
    private int type = 0;//0首次加载 1下拉刷新 2上拉加载更多

    private int errorType=-1;//遇到错误时显示的页面 0定位失败

    public RecyclerView getRecyclerView() {
        return recyclerView;
    }

    public int getErrorType() {
        return errorType;
    }

    public void setErrorType(int errorType) {
        this.errorType = errorType;
    }

    /**
     * @author 定义服务器返回状态
     */
    public enum LoadResult {
        error(2), empty(3), success(4);
        int value;

        LoadResult(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

    public View getRootView() {
        return rootView;
    }

    public BaseListPage(Context context) {
        this.context = context;
        rootView = View.inflate(context, R.layout.base_list_page, null);
        recyclerView = rootView.findViewById(R.id.recyclerView);
        llEmpty = rootView.findViewById(R.id.ll_empty);
        llError = rootView.findViewById(R.id.ll_error);
        refresh = rootView.findViewById(R.id.refresh);
        flLoading = rootView.findViewById(R.id.fl_loading);
        flLoading.addView(createLoadingView());
        llEmpty.addView(createEmptyView());
        llError.addView(createErrorView());

        data = new ArrayList<>();
        refresh.setColorSchemeResources(R.color.owner_blue);
        refresh.setOnRefreshListener(this::onRefresh);
    }


    public View createEmptyView() {
        View view = View.inflate(CommUtils.getContext(),
                R.layout.empty_pager_layout, null);
        return view;
    }

    public View createErrorView() {
        View view = View.inflate(CommUtils.getContext(),
                R.layout.error_pager_layout, null);
        Button bt_errprpager = (Button) view.findViewById(R.id.bt_errprpager);
        bt_errprpager.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                onRefresh();// 重新加载
                LogMds.i("cdz", "createErrorView");
            }


        });
        LogMds.i("cdz", "createErrorView");
        return view;
    }
    public String getLocationErrorTip(){
        return "开启定位可查看附近卡站";
    }
    public View createLocationErrorView() {

        return null;
    }

    private View createLoadingView() {
        View view = View.inflate(CommUtils.getContext(),
                R.layout.loading_pager_layout, null);
        return view;
    }
    public static final int ON_LOADING=0x01;//加载中
    public static final int ON_FINISH=0x02;//加载完成

    private int count = 0;
    private int myStatus;


    public void showPage() {
        if (myStatus==ON_LOADING) {
            return;
        }
        myStatus=ON_LOADING;
        showLoading();
        if (callBack == null) {
            callBack = new GetDataCallBack<T>() {
                @Override
                public void onSuccess(List<T> list) {
                    if (list == null || list.size() == 0) {
                        refreshUi(LoadResult.empty, list);
                    } else {
                        refreshUi(LoadResult.success, list);
                    }
                }

                @Override
                public void onError() {
                    refreshUi(LoadResult.error, null);
                }
            };
        }
        getData(callBack);
    }

    public void showErrorView(){
        refreshUi(LoadResult.error, null);
    }

    private void refreshUi(LoadResult status, List<T> list) {
        if (LoadResult.success.getValue() == status.getValue()) {
            if (list == null || list.size() == 0) {
                showEmpty();
            } else {
                fillData(list);
            }
        } else if (LoadResult.empty.getValue() == status.getValue()) {
            showEmpty();
        } else {
            showError();
        }
        if (refresh.isRefreshing()) {
            refresh.setRefreshing(false);
        }
        myStatus=ON_FINISH;
    }
    public RecyclerView.LayoutManager getLayoutManager(Context context){
        return new LinearLayoutManager(context);
    }
    public View getHeaderView(){
        return null;
    }

    private void fillData(List<T> list) {
        llEmpty.setVisibility(View.GONE);
        llError.setVisibility(View.GONE);
        flLoading.setVisibility(View.GONE);
        refresh.setVisibility(View.VISIBLE);
        if (adapter == null) {
            data.addAll(list);
            adapter = getAdapter(data);
            RecyclerView.LayoutManager layoutManager=getLayoutManager(context);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(adapter);
            adapter.bindToRecyclerView(recyclerView);
            View headerView = getHeaderView();
            if (headerView != null) {
                adapter.addHeaderView(headerView);
            }
            setOnLoadMoreListener();
        } else {
            if (type == 1) {
                //刷新
                data.clear();
            } else if (type == 2) {
                //上拉加载更多
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        //成功获取更多数据
                        if (data.size() > 100) {
                            adapter.loadMoreEnd();
                        } else if (data.size() % 2 == 0) {
                            adapter.loadMoreFail();
                        } else {
                            adapter.loadMoreComplete();
                        }

                    }
                });
            }
            data.addAll(list);
            //            adapter.addData(list);
            adapter.notifyDataSetChanged();
        }
        type = 0;
    }

    private void showEmpty() {
        flLoading.setVisibility(View.GONE);
        llEmpty.setVisibility(View.VISIBLE);
        llError.setVisibility(View.GONE);
        refresh.setVisibility(View.GONE);
    }

    private void showError() {
        flLoading.setVisibility(View.GONE);
        llEmpty.setVisibility(View.GONE);
        llError.removeAllViews();
        if (errorType==-1) {
            llError.addView(createErrorView());
        }else if(errorType==0){
            llError.addView(createLocationErrorView());
        }
        llError.setVisibility(View.VISIBLE);
        refresh.setVisibility(View.GONE);
    }
    public void setErrorViewMarginTop(int marginTopDp){
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) llError.getLayoutParams();
        layoutParams.topMargin= UIUtils.dip2px(marginTopDp);
        llError.requestLayout();
    }

    private void showLoading() {
        llEmpty.setVisibility(View.GONE);
        llError.setVisibility(View.GONE);
        refresh.setVisibility(View.GONE);
        flLoading.setVisibility(View.VISIBLE);
    }

    //是否上拉加载 默认上拉加载
    public void setIsLoadMore(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
    }

    //设置上拉加载模式 调用该方法后列表能够上拉加载
    private void setOnLoadMoreListener() {
        if (!isLoadMore) {
            return;
        }
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                type = 2;
                showPage();
            }
        }, recyclerView);
        adapter.disableLoadMoreIfNotFullPage();//避免默认第一次加载进入上拉加载
    }

    public void onRefresh() {
        type = 1;
        showPage();
    }

    public abstract BaseQuickAdapter getAdapter(List<T> list);

    public BaseQuickAdapter getAdapter() {
        return adapter;
    }

    /**
     * 获取数据
     */
    public abstract void getData(GetDataCallBack<T> callBack);

    public static interface GetDataCallBack<T> {
        void onSuccess(List<T> list);

        void onError();
    }

}

